<template>
  <Panel>
    <!-- 标题 -->
    <template #title>
      <span>账号列表</span>
    </template>
    <!-- 内容 -->
    <template>
      <!-- 1.0 表格 -->
      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        size="small"
        border
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="account" label="账号"> </el-table-column>
        <el-table-column prop="userGroup" label="用户组"> </el-table-column>
        <el-table-column prop="ctime" label="创建时间">
          <template v-slot="{ row }">
            {{ row.ctime | format }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <!-- 使用插槽显示按钮 -->
          <template v-slot="{ row }">
            <el-button size="mini" type="primary" @click="showItem(row)"
              >编辑</el-button
            >
            <el-button size="mini" type="danger" @click="delUsers(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 2.0 分页的处理 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
      <!-- 3.0 按钮的操作 -->
      <el-button
        size="small"
        type="danger"
        :loading="listFlag"
        @click="everyDel()"
        >批量删除</el-button
      >
      <el-button size="small" @click="toggleSelection()" type="primary"
        >取消选择</el-button
      >
      <!-- 编辑区域 -->
      <el-dialog title="提示" :visible.sync="dialogVisible" width="50%">
        <div>
          <el-form
            :model="editForm"
            status-icon
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
            size="small"
          >
            <!-- 账号 -->
            <el-form-item label="账号" prop="account">
              <el-input
                type="text"
                v-model="editForm.account"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <!-- 下拉框 -->
            <el-form-item label="用户组" prop="userGroup">
              <el-select
                v-model="editForm.userGroup"
                size="small"
                placeholder="请选择用户组"
              >
                <el-option label="普通管理员" value="普通管理员"> </el-option>
                <el-option label="超级管理员" value="超级管理员"> </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="resetForm('ruleForm')">取 消</el-button>
          <el-button type="primary" @click="editUser('ruleForm')"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </template>
  </Panel>
</template>

<script>
import { validateUname, validateGroup } from '@/utils/validator.js'
import {
  AccountList,
  delAccount,
  everyDelAccount,
  editUsers
} from '@/api/users.js'
import Aa from 'sortablejs'
export default {
  data() {
    return {
      listFlag: false,
      // 分页的数据
      currentPage: 1,
      pageSize: 5,
      total: 0,
      tableData: [],
      multipleSelection: [],
      dialogVisible: false,
      editForm: {
        account: '',
        userGroup: ''
      },
      rules: {
        account: [
          { required: true, validator: validateUname, trigger: 'blur' }
        ],
        userGroup: [
          { required: true, validator: validateGroup, trigger: 'change' }
        ]
      }
    }
  },
  // 页面一加载就发送请求
  created() {
    this.getUsers()
  },
  mounted() {
    // 拖拽
    const el = document.querySelector('.el-table tbody')
    /* eslint-disable no-new */
    new Aa(el, {
      animation: 150,
      draggable: '.el-table__row'
    })
  },
  methods: {
    // 获取数据
    async getUsers() {
      const { data, total } = await AccountList({
        currentPage: this.currentPage,
        pageSize: this.pageSize
      })
      // console.log(data)
      this.tableData = data
      this.total = total
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.getUsers()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getUsers()
    },
    // 删除指定的用户
    delUsers(id) {
      this.$confirm('此操作将永久删除账号, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          // 删除成功的回调
          const { code, msg } = await delAccount({ id })
          // console.log(data)
          if (code === 0) {
            this.$message.success(msg)
            this.getUsers()
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 批量删除
    everyDel() {
      const newIds = JSON.stringify(this.multipleSelection.map(item => item.id))
      // console.log(newIds)
      if (this.multipleSelection.length > 0) {
        this.$confirm('此操作将永久删除账号, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            // 批量删除成功的回调
            const { code, msg } = await everyDelAccount({
              ids: newIds
            })
            if (code === 0) {
              this.$message.success(msg)
              this.getUsers()
            }
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
      } else {
        this.$message.error('请选择要删除的管理员')
        this.listFlag = true
        setTimeout(() => {
          this.listFlag = false
        }, 3000)
      }
    },
    // 数据回显
    showItem(row) {
      this.editForm = { ...row }
      // console.log(this.editForm)
      this.dialogVisible = true
    },
    // 修改编辑
    editUser(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          // 验证通过,可以发请求了
          const { code, msg } = await editUsers({
            id: this.editForm.id,
            account: this.editForm.account,
            userGroup: this.editForm.userGroup
          })
          if (code === 0) {
            this.$message.success(msg)
            this.dialogVisible = false
            this.getUsers()
            location.reload()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.dialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-table {
  margin: 20px 0px 20px;
}
.el-input,
.el-select {
  width: 200px;
}
.el-table {
  cursor: pointer;
}
</style>
